import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.MouseEvent;
import flash.events.Event;
import AVerletModel;
import TileModel;

class MainCharacterController 
{
  static private var EASING:Float = .2;
  static private var JUMP_FORCE:Float = -25;
  static private var SPEED_LIMIT:Float = 10;
  private var _model:MainCharacterModel;
  private var _stage:Dynamic;
  private var _mouse_Vx:Float;
  private var _mouse_Vy:Float;
  private var mKeyDown:Array<Bool>;

  public function new(model:MainCharacterModel)
  {
    _model = model;
    _mouse_Vx =0;_mouse_Vy = 0;
    mKeyDown = [];
  }
  public function processKeyChange()
  {
    if(mKeyDown[Keyboard.LEFT])
    {
      _model.acceleration_X = -5;
      _model.direction = "Left";
    }
    else if(mKeyDown[Keyboard.RIGHT])
    {
      _model.acceleration_X = 5;
      _model.direction = "Right";
    }
    else if(!mKeyDown[Keyboard.RIGHT] && !mKeyDown[Keyboard.LEFT])
    {
      _model.acceleration_X = 0 ;
    }
    if(mKeyDown[Keyboard.SPACE]
    || mKeyDown[Keyboard.UP])
    {
      jump();
    }
    else if(!mKeyDown[Keyboard.SPACE]
    && !mKeyDown[Keyboard.UP])
    {
      _model.acceleration_Y = 0 ;
    }
    if(mKeyDown[Keyboard.ENTER])
    {
      _model.exit = true;
    }
    
  }
  public function processKeyDown(event:KeyboardEvent)
  {
    if(!mKeyDown[event.keyCode])
    {
      mKeyDown[event.keyCode] =true;
      processKeyChange();
    }
  }


  public function processKeyUp(event:KeyboardEvent)
  {
    mKeyDown[event.keyCode] = false;
  }
  
  public function processUpdate
    (stage:Dynamic)
  {
    processKeyChange();
    if(_model.acceleration_X == 0)
    { _model.vx = _model.vx *.5;
    }
    if(_model.vx < -SPEED_LIMIT)
    {  
      _model.vx = -SPEED_LIMIT;
    }
    if(_model.vx > SPEED_LIMIT)
    {  
      _model.vx = SPEED_LIMIT;
    }
  }
  
  public function processMouseDown
    (event:MouseEvent)
  {
    _model.firing = 2;
    _model.Shot = true;
    // trace("y = " + m + "x +" + b);
  }

  public function processMouseUp
    (event:MouseEvent)
  {
    _model.firing = 0;
    // trace("y = " + m + "x +" + b);
  }
  
  public function jump()
  {
    if(_model.jumping < 2 && _model.vy > 0)
    {
      _model.jumping++;
      _model.vy = JUMP_FORCE;
    }
  }
}